package vip.xiaonuo.issued.task;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.common.utils.DateUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.core.util.DateUtils;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.rule.DwRulesEngine;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
public class DeviceHeartBeatTask implements TimerTaskRunner {

  private static final CopyOnWriteArraySet<String> currentExecuteTask = new CopyOnWriteArraySet();


  @Autowired
  private DeviceBaseService deviceBaseService;



  @Override
  public void action(String jobParams,String taskId) {
    localExecute(taskId);
  }

  private void localExecute(String taskId) {
    synchronized (DeviceHeartBeatTask.class) {
      if (currentExecuteTask.contains(taskId)) {
        log.error("当前任务正在执行请稍后！");
        return;
      }
      log.info("心跳任务开始执行" + taskId + DateUtil.formatAlternativeIso8601Date(new Date()));
      currentExecuteTask.add(taskId);
    }
    // 心跳
    heartBeat();
    log.info("心跳任务执行结束" + taskId);
    currentExecuteTask.remove(taskId);
  }

  @Override
  @XxlJob("DeviceHeartBeatTask")
  public void executeXxlJob() {
    // 心跳
    heartBeat();
  }

  private void heartBeat() {
    List<DeviceBase> deviceBases = deviceBaseService.list();
    for (DeviceBase deviceBase : deviceBases) {
      if (ObjectUtil.equal(deviceBase.getDeviceType(),6)){
        log.debug("访客机心跳 非主动查询!");
        continue;
      }
      if (StringUtils.isBlank(deviceBase.getCabinetIp()) && StringUtils.isBlank(deviceBase.getCabinetPort())&&!ObjectUtil.equal(deviceBase.getDeviceType(),"5")) {
        log.error("设备未设置ip和端口不进行操作!");
        continue;
      }

      if (ObjectUtil.equal(deviceBase.getDeviceType(),"10")){
        log.debug("鸿图设备 单独处理心跳!");
        continue;
      }

      try {
        Date lastOnlineTime = deviceBase.getLastOnlineTime();
        if (lastOnlineTime!=null&&DateUtils.addMinutes(new Date(), -3).after(lastOnlineTime)) {
          downDevice(deviceBase);
        }
        // 发送消息
        DwRulesEngine.faceDoorDtoService.getDeviceState(deviceBase.getId().toString());
      } catch (Exception e) {
        e.printStackTrace();
        log.error("设备心跳发生错误【{}】", ExceptionUtils.getMessage(e));
        downDevice(deviceBase);
      }
    }
  }

  private void downDevice(DeviceBase deviceBase) {
    log.error("设备下线！" + deviceBase.getName());
    deviceBase.setDeviceState("2");
    deviceBaseService.updateById(deviceBase);
  }
}
